package com.sm.auth.utils;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sm.auth.vo.LoginUserVo;
import com.sm.common.constants.CacheConstants;
import com.sm.support.config.utils.RedisCacheUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JwtUtil {
    @Autowired
    private RedisCacheUtil  redisCacheUtil;
    //盐值
    public static final String SECRET = "fantasyBaby";

    /**
     * 创建token，并将用户数据存放到redis中
     * 可以方便实现单点登录，踢人下线
     * 可以使用UUID作为redis中的key
     */
    public String createToken(LoginUserVo loginUserVo){
        String strUUID = UUID.randomUUID().toString().replaceAll("-", "");
        //把生成的uuid作为LoginUserVo对象的token属性值，可以通过该值从redis中获取用户数据
        loginUserVo.setToken(strUUID);
        HashMap<String, Object> claims = new HashMap<>();
        //把uuid进行编码生成token
        claims.put("strUUID",strUUID);
        //把此处的token作为redis的key，loginUserVo作为redis的value
        redisCacheUtil.setCacheObject(CacheConstants.LOGIN_USER_KEY+strUUID,loginUserVo,30, TimeUnit.MINUTES);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }
    /**
     * 解析token
     */
    public Claims parseToken(String token){
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }
    /**
     * 根据token，解析uuid，从redis中获取用户数据
     */
    public LoginUserVo getLoginUser(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(StringUtils.isNotEmpty( token)){
            Claims claims = parseToken(token);
            LoginUserVo loginUserVo = redisCacheUtil.getCacheObject(CacheConstants.LOGIN_USER_KEY + claims.get("strUUID"));
            log.info("loginUserVo:{}",loginUserVo);
            //如果token有效，则刷新token并返回用户数据
            if(ObjectUtil.isNotNull(loginUserVo)){
                refreshToken(loginUserVo);
                return loginUserVo;
            }
        }
        return null;
    }
    /**
     * 刷新token
     */
    public void refreshToken(LoginUserVo loginUserVo){
        redisCacheUtil.setCacheObject(CacheConstants.LOGIN_USER_KEY+loginUserVo.getToken(),loginUserVo,30, TimeUnit.MINUTES);
    }
}


